<template>
	<!-- 动画时间尽量短，如果太长触发@animationfinish很慢 -->
	<!-- :indicator-dots="true" -->
	<swiper @animationfinish="swiperAnimationfinish" :current-item-id="String(current_item_id)" :autoplay="false" :duration="150">
		<swiper-item v-for="i in arr_img.value" :key="i.id" :item-id="String(i.id)">
			<image :src="i.url" mode="aspectFill"></image>
		</swiper-item>
	</swiper>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { inject, nextTick, reactive, ref, watch } from 'vue'
import { get_image_data_list_by_id, get_image_data_by_id } from '@/api'

const current_item_id = ref()
const arr_img = reactive({ value: [] })
const current_item_index = inject('current_item_index')
const current_image_data = inject('current_image_data')

const api_get_image_data_list_by_id = async function (dir = null, update_limit = 3) {
	if (dir == 'head') {
		let res = await get_image_data_list_by_id(arr_img.value[0].category, arr_img.value[0].id, update_limit, dir)
		arr_img.value = [...res.data, ...arr_img.value]
	} else {
		let res = await get_image_data_list_by_id(arr_img.value[0].category, arr_img.value[arr_img.value.length - 1].id, update_limit)
		arr_img.value = [...arr_img.value, ...res.data]
	}
}

const swiperAnimationfinish = (event) => {
	let old_index = arr_img.value.findIndex((item) => item.id == current_item_id.value)
	let new_index = arr_img.value.findIndex((item) => item.id == event.detail.currentItemId)
	// console.log('之前的索引=', old_index, ' 新的索引=', new_index)
	current_item_index.value += new_index - old_index

	current_item_id.value = event.detail.currentItemId

	current_image_data.value = arr_img.value.find((item) => item.id == event.detail.currentItemId)

	if (event.detail.current <= 1) {
		console.log('到了最左边')
		api_get_image_data_list_by_id('head')
	} else if (event.detail.current >= arr_img.value.length - 2) {
		console.log('到了最右边')
		api_get_image_data_list_by_id()
	}
	// preview_index.value += event.detail.current - swiper_current.value
}

const init_arr_img = async function (id) {
	let res = await get_image_data_by_id(id)
	arr_img.value = [res.data]
	current_image_data.value = res.data
}

onLoad((obj) => {
	current_item_id.value = obj.id

	init_arr_img(obj.id).then(() => {
		api_get_image_data_list_by_id('head', 2)
		api_get_image_data_list_by_id(null, 2)
	})
})
</script>

<style scoped lang="scss">
swiper {
	position: absolute;
	top: 0%;
	left: 0%;
	width: 100%;
	height: 100%;

	swiper-item {
		image {
			width: 100%;
			height: 100%;
		}
	}
}
</style>
